﻿using Microsoft.Xna.Framework;
using System;

namespace SharpDepend.WP8
{
    class KeyboardManager : IKeyboardManager
    {
        private KeyboardTextChanged s_onTextChanged;
        private string s_lastDefaultText = string.Empty;

        public event KeyPressedHandler OnKeyPressed;

        public bool IsKeyDown(Key key)
        {
            return false;
        }

        public void ShowVirtualKeyboard(string titleHint, string descriptionHint, string defaultText, KeyboardTextChanged onTextChanged)
        {
            // Reset all events.
            s_onTextChanged = null;

            // Insert the latest one.
            s_onTextChanged += onTextChanged;

            // Show the keyboard for WP7/8
            Microsoft.Xna.Framework.GamerServices.Guide.BeginShowKeyboardInput(
                   PlayerIndex.One,
                   titleHint, //"Save project",
                   descriptionHint, //"Insert your name of the project file",
                   defaultText,
                   OnEndShowKeyboardInput,
                   null);

            s_lastDefaultText = defaultText;
        }
        
        public KeybordSupport KeybordSupport
        {
            get
            {
                return KeybordSupport.VirtualKeyboard;
            }
        }

        //------------------------------------------------------------------------------------------------------------------------
        private void OnEndShowKeyboardInput(IAsyncResult result)
        {
            string insert = Microsoft.Xna.Framework.GamerServices.Guide.EndShowKeyboardInput(result);
            if (string.IsNullOrWhiteSpace(insert))
            {
                if (s_onTextChanged != null)
                {
                    s_onTextChanged(s_lastDefaultText);
                }
            }
            else
            {
                if (s_onTextChanged != null)
                {
                    s_onTextChanged(insert.Replace("\n\r", "\n").Replace("\r", "\n")); // Only use \n.
                }
            }
        }
    }
}
